const mes = localStorage.getItem("mes")
const up_address = JSON.parse(mes)
let addArr = []
addArr.push(...up_address)
let address = localStorage.getItem('address');
let arr1 = JSON.parse(address) || []

// 添加地址弹框显示
document.querySelector(".action").addEventListener("click", function (e) {
    if (e.target.tagName === "BUTTON") {
        if (e.target.dataset.name === "insert") {
            document.querySelector(".insert").style.zIndex = "3"
            document.querySelector(".pop_con").style.opacity = "1"
        }
    }
})
// 弹框隐藏
document.querySelector(".cancel").addEventListener("click", function () {
    document.querySelector(".insert").style.zIndex = "-1"
    document.querySelector(".pop_con").style.opacity = "0"
})
document.querySelector(".btn_cancel").addEventListener("click", function () {
    document.querySelector(".insert").style.zIndex = "-1"
    document.querySelector(".pop_con").style.opacity = "0"
})
document.querySelector(".exchange_cancel").addEventListener("click", function () {
    document.querySelector(".exchange").style.zIndex = "-1"
    document.querySelector(".exchange .pop_con").style.opacity = "0"
})
document.querySelector(".exchange_btncancel").addEventListener("click", function () {
    document.querySelector(".exchange").style.zIndex = "-1"
    document.querySelector(".exchange .pop_con").style.opacity = "0"
})
document.querySelector(".up_can").addEventListener("click", function () {
    document.querySelector(".updata").style.zIndex = "-1"
    document.querySelector(".updata .pop_con").style.opacity = "0"
})
document.querySelector(".up_cancel").addEventListener("click", function () {
    document.querySelector(".updata").style.zIndex = "-1"
    document.querySelector(".updata .pop_con").style.opacity = "0"
})
//  地址下拉选框
//配送地址
//获取下拉框
let proValue = null
let cityValue = null
let distValue = null
let province = document.getElementById("province");
let city = document.getElementById("city");
let district = document.getElementById("district");
let frag = document.createDocumentFragment();
//循环遍历地址
for (let i = 0; i < data.length; i++) {
    let option = document.createElement("option");
    option.innerHTML = data[i].name;
    option.value = data[i].code;
    frag.appendChild(option);
}

//省级数据添加到下拉框
province.appendChild(frag);
//存放市的数据
let cityArr = []
//省的数据变化触发该事件
province.addEventListener('change', function () {
    //清空市和区的数据，以防重复
    city.innerHTML = `<option value="">---请选择---</option>`
    district.innerHTML = `<option value="">---请选择---</option>`
    //循环遍历数据，将遍历的数据和当前省份作比较
    for (let i = 0; i < data.length; i++) {
        if (data[i].code == this.value) {
            cityArr = data[i].children;
            proValue = data[i].name
            break;
        }
    }

    console.log(proValue);
    //遍历市级数据
    for (let j = 0; j < cityArr.length; j++) {
        let option = document.createElement("option");
        option.innerHTML = cityArr[j].name;
        option.value = cityArr[j].code;
        frag.appendChild(option);
    }
    city.appendChild(frag);
})
//存放区的数据
let districtArr = []
city.addEventListener('change', function () {
    //清除区的数据，以防重复
    district.innerHTML = `<option value="">---请选择---</option>`
    //循环遍历数据，将遍历的数据和当前市级作比较
    for (let i = 0; i < cityArr.length; i++) {
        if (cityArr[i].code == this.value) {
            districtArr = cityArr[i].children;
            cityValue = cityArr[i].name
            distValue = districtArr[i].name
            break;
        }
    }
    //遍历区级数据
    for (let j = 0; j < districtArr.length; j++) {
        let option = document.createElement("option");
        option.innerHTML = districtArr[j].name;
        option.value = districtArr[j].code;
        frag.appendChild(option);

    }
    district.appendChild(frag);
})


// 表单验证
const usernameEle = document.querySelector('input[name="username"]')
function verifyUsername() {
    const reg = /^[a-zA-Z0-9-_]{6,10}$/
    if (reg.test(usernameEle.value) !== true) {
        usernameEle.nextElementSibling.innerHTML = '用户名不符合要求'
        return false
    } else {
        usernameEle.nextElementSibling.innerHTML = ""
        return true
    }
}
usernameEle.addEventListener('change', verifyUsername)

const phoneEle = document.querySelector('input[name="phone"]')
function verifyPhone() {
    const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
    if (reg.test(phoneEle.value) !== true) {
        phoneEle.nextElementSibling.innerHTML = '手机号不符合要求'
        return false
    } else {
        phoneEle.nextElementSibling.innerHTML = ""
        return true
    }
}
phoneEle.addEventListener('change', verifyPhone)

const addressEle = document.querySelector('.box_address')
function verifyAddress() {
    const reg = /\S/
    if (reg.test(province) !== true && reg.test(city) !== true && reg.test(district) !== true) {
        addressEle.nextElementSibling.innerHTML = '请选择地址'
        return false
    } else {
        addressEle.nextElementSibling.innerHTML = ""
        return true
    }
}
addressEle.addEventListener('change', verifyAddress)

const totalAddEle = document.querySelector('input[name="totalAdd"]')
function verifyTotalAdd() {
    const reg = /\S/
    if (reg.test(totalAddEle.value) !== true) {
        totalAddEle.nextElementSibling.innerHTML = '地址不为空'
        return false
    } else {
        totalAddEle.nextElementSibling.innerHTML = ""
        return true
    }
}
totalAddEle.addEventListener('change', verifyTotalAdd)
// 总体提交表单判断
const form = document.querySelector(".xtx_form")
form.addEventListener("submit", function (e) {
    e.preventDefault()
    const ret1 = verifyUsername()
    if (!ret1) {
        return
    }
    const ret2 = verifyPhone()
    if (!ret2) {
        return
    }
    const ret3 = verifyAddress()
    if (!ret3) {
        return
    }
    const ret4 = verifyTotalAdd()
    if (!ret4) {
        return
    }
    alert("添加成功")
    let obj = {
        name: usernameEle.value,
        tel: phoneEle.value,
        proValue: proValue,
        cityValue: cityValue,
        distValue: distValue,
        addelt: totalAddEle.value
    }
    arr1.push(obj)
    localStorage.setItem("address", JSON.stringify(arr1))
    form.reset()
    document.querySelector(".insert").style.zIndex = "-1"
    document.querySelector(".pop_con").style.opacity = "0"
})
// 切换地址数据渲染
const exchange = document.querySelector(".exchange")
document.querySelector(".action").addEventListener("click", function (e) {
    if (e.target.tagName === "BUTTON") {
        if (e.target.dataset.name === "exchange") {
            exchange.style.zIndex = "3"
            document.querySelector(".exchange .pop_con").style.opacity = "1"
            rendon(arr1)
        }
    }
})
// 切换地址数据渲染函数
function rendon(arr) {
    let newArr = arr.reduce(function (prev, item, index) {
        return prev + ` 
    <div data-index=${index} class="form_list">
        <ul>
            <li>
                <span>收货姓名：</span>
                <span>${item.name}</span>
            </li>
            <li>
                <span>联系方式：</span>
                <span>${item.tel}</span>
            </li>
            <li>
                <span>收货地址：</span>
                <span>${item.proValue}${item.cityValue}${item.distValue}${item.addelt}</span>
            </li>
        </ul>
    </div>
        ` }, "")
    document.querySelector(".list_body").innerHTML = newArr
}
// 选中地址添加active，其余移除active
const list = document.querySelector(".list_body")
let newStr = null
list.addEventListener("click", e => {
    for (let i = 0; i < list.children.length; i++) {
        if (e.target.tagName === "SPAN") {
            for (let j = 0; j < list.children.length; j++) {
                if (list.querySelector(".active")) {
                    list.querySelector(".active").classList.remove("active")
                }
                list.children[+e.target.parentNode.parentNode.parentNode.dataset.index].classList.add("active")
                newStr = +e.target.parentNode.parentNode.parentNode.dataset.index
            }
        }
    }
})

// 切换地址数据渲染在页面中
document.querySelector(".exchange_form").addEventListener("submit", function (e) {
    e.preventDefault()
    if (list.nextElementSibling.children[1].dataset.name === "confirm") {
        if (list.children.length) {
            exchange.style.zIndex = "-1"
            document.querySelector(".pop_con").style.opacity = "0"
            document.querySelector(".none").style.display = "none"
            document.querySelector(".add_block").style.display = "block"
            // document.querySelector(".up_add").style.display = "block"
            document.querySelector(".add_name").innerHTML = `${arr1[newStr].name}`
            document.querySelector(".add_phone").innerHTML = `${arr1[newStr].tel}`
            document.querySelector(".add_address").innerHTML = `${arr1[newStr].proValue}${arr1[newStr].cityValue}${arr1[newStr].distValue}${arr1[newStr].addelt}`
        }
    }
})

// 修改地址页面渲染
document.querySelector(".up_addblock").addEventListener("click", function () {
    const updata = document.querySelector(".updata")
    // const btnConfirm = document.querySelector(".up_confirm")
    updata.style.zIndex = "3"
    document.querySelector(".updata .pop_con").style.opacity = "1"
    if (updata.style.zIndex === "3") {
        document.querySelector('input[name="up_username"]').value = `${arr1[newStr].name}`
        document.querySelector('input[name="up_phone"]').value = `${arr1[newStr].tel}`
        document.getElementById("up_province").value = `${arr1[newStr].proValue}`
        document.getElementById("up_city").value = `${arr1[newStr].cityValue}`
        document.getElementById("up_district").value = `${arr1[newStr].distValue}`
        document.querySelector('input[name="up_totalAdd"]').value = `${arr1[newStr].addelt}`
    }
})

// 修改地址下拉选框地址渲染
let upproValue = null
let upcityValue = null
let updistValue = null
let upprovince = document.getElementById("up_province");
let upcity = document.getElementById("up_city");
let updistrict = document.getElementById("up_district");
let frag1 = document.createDocumentFragment();
//循环遍历地址
for (let i = 0; i < data.length; i++) {
    let option = document.createElement("option");
    option.innerHTML = data[i].name;
    option.value = data[i].code;
    frag1.appendChild(option);
}

//省级数据添加到下拉框
upprovince.appendChild(frag1);
//存放市的数据
let upcityArr = []
//省的数据变化触发该事件
upprovince.addEventListener('change', function () {
    //清空市和区的数据，以防重复
    upcity.innerHTML = `< option value = "" > --- 请选择-- -</ > `
    updistrict.innerHTML = `< option value = "" > --- 请选择-- -</ > `
    //循环遍历数据，将遍历的数据和当前省份作比较
    for (let i = 0; i < data.length; i++) {
        if (data[i].code == this.value) {
            upcityArr = data[i].children;
            upproValue = data[i].name
            break;
        }
    }

    //遍历市级数据
    for (let j = 0; j < upcityArr.length; j++) {
        let option = document.createElement("option");
        option.innerHTML = upcityArr[j].name;
        option.value = upcityArr[j].code;
        frag1.appendChild(option);
    }
    upcity.appendChild(frag1);
})
//存放区的数据
let updistrictArr = []
upcity.addEventListener('change', function () {
    //清除区的数据，以防重复
    updistrict.innerHTML = `< option value = "" > --- 请选择-- -</ > `
    //循环遍历数据，将遍历的数据和当前市级作比较
    for (let i = 0; i < upcityArr.length; i++) {
        if (upcityArr[i].code == this.value) {
            updistrictArr = upcityArr[i].children;
            upcityValue = upcityArr[i].name
            updistValue = updistrictArr[i].name
            break;
        }
    }
    //遍历区级数据
    for (let j = 0; j < updistrictArr.length; j++) {
        let option = document.createElement("option");
        option.innerHTML = updistrictArr[j].name;
        option.value = updistrictArr[j].code;
        frag1.appendChild(option);
    }
    updistrict.appendChild(frag1);
})

document.querySelector(".up_form").addEventListener("submit", function (e) {
    e.preventDefault()
    document.querySelector(".updata").style.zIndex = "-1"
})

function render(arr) {
    const newArr = arr.filter(e => e.checked === true)
    const newStr = newArr.reduce((prev, item) => {
        return prev + `
         <tr>
                                    <td>
                                        <a href="jacascript:;">
                                            <div class="left_pic">
                                                <img src="${item.goodsPicture}" alt="">
                                            </div>
                                            <div class="shoptext">
                                                <p>${item.goodsName}</p>
                                                <p>规格：${item.titleFir}</p>
                                            </div>
                                        </a>
                                    </td>
                                    <td>￥<i>${item.goodsPrice}</i></td>
                                    <td>${item.goodsCount}</td>
                                    <td>￥<i>${item.goodsPrice * item.goodsCount}</i></td>
                                    <td>￥<i>${item.goodsPrice * item.goodsCount}</i></td>
                                </tr> ` }, "")
    document.querySelector("tbody").innerHTML = newStr
    const num = newArr.reduce((prev, item) => prev + +item.goodsCount, 0)
    document.querySelector(".shop_count").innerHTML = num
    const amount = newArr.reduce((prev, item) => prev + +item.goodsPrice, 0)
    document.querySelector(".shop_amount").innerHTML = amount
    document.querySelector(".shop_pay").innerHTML = amount
}
render(addArr)
// 点击结算页面跳转
document.querySelector(".xtx_submit").addEventListener("click", function () {
    location.href = "../html/pay.html"
})
shoppingsss(goodArr)

let username = localStorage.getItem("uname")

const li1 = document.querySelector(".xtx_navs li:nth-child(1)")
const li2 = document.querySelector(".xtx_navs li:nth-child(2)")
if (username) {
    li1.innerHTML = `<a href="javascript:;"><i class="iconfont icon-user">${username}</i></a>`
    li2.innerHTML = '<a href="javascript:;">退出登录</a>'
} else {
    li1.innerHTML = '<a href="../html/login.html">请先登录</a>'
    li2.innerHTML = '<a href="../html/register.html">免费注册</a>'
}
// 退出登录
li2.addEventListener("click", function () {
    // 退出登录
    //  删除localStroage的uuu的数据
    localStorage.removeItem("uname")
    location.reload(true)
})